package com.sitech.openapi.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sitech.openapi.componet.SoapClientService;
import com.sitech.openapi.componet.WSClientService;
import com.sitech.openapi.dto.ProdPreOrder;
import com.sitech.openapi.dto.ProdPreOrderExample;
import com.sitech.openapi.mapper.InvoiceInfoMapper;
import com.sitech.openapi.mapper.ProdPreOrderMapper;
import com.sitech.openapi.mapper.ProdPreOrderMapperService;
import com.sitech.openapi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * Created by zhangsq on 2018/12/7.
 * 关于随选宽带甩单集约销售支撑工作的通知需求
 * 查询客户订单物流信息
 */
@Service
@Slf4j
public class CustOrderLogisticsServiceImpl implements CustOrderLogisticsService {

    @Autowired
    private ProdPreOrderMapper prodPreOrderMapper;
    @Autowired
    WSClientService wsClientService;
    @Autowired
    private SoapClientService soapClientService;
    @Autowired
    private InvoiceInfoMapper invoiceInfoMapper;
    @Autowired
    private ProdPreOrderMapperService prodPreOrderMapperService;
    @Autowired
    private ObjectMapper mapper;

    public List queryCustOrderLogistics(Map inMap) throws Exception {
        int cnt = 0;
        List<Map> retList = new ArrayList();
        try {
            log.info("#######################queryCustOrderLogistics开始"+inMap);
            String extCustOrderId = StringUtil.obj2Str(inMap.get("extCustOrderId"));
            String commonRegionId =  StringUtil.obj2Str(inMap.get("commonRegionId"));

            ProdPreOrderExample prodPreOrderExample = new ProdPreOrderExample();
            prodPreOrderExample.createCriteria().andExtCustOrderIdEqualTo(extCustOrderId);
            prodPreOrderExample.createCriteria().andAccNbrTypeCdEqualTo("4");
            //更新历史表内的记录
            List<ProdPreOrder> prodPreOrderList = prodPreOrderMapper.selectByExampleWithBLOBs(prodPreOrderExample);
            ProdPreOrder prodPreOrder = new ProdPreOrder();
            if (prodPreOrderList != null && prodPreOrderList.size() > 0) {
                prodPreOrder = prodPreOrderList.get(0);
                String clob = prodPreOrder.getInParam();
                Map<String, Object> clobMap = mapper.readValue(clob, Map.class);
                Map prodPreOrderMap = (Map) clobMap.get("prodPreOrder");
                Map retMap = (Map) prodPreOrderMap.get("custOrderLogistics");
                if(StringUtil.isEmptyOrNull(prodPreOrder.getLogisticsNbr())){
                    throw new RuntimeException("未生成物流信息！");
                }
                retMap.put("logisticsNbr", prodPreOrder.getLogisticsNbr());
                retMap.put("logisticsCompany", prodPreOrder.getLogisticsCompany());
                //add by yinjj 调ems物流信息
                //增加开关,如果关闭，则不调ems接口；如果开启，则调ems接口
                Map kgMap = new HashMap<>();
                String retString = "";
                kgMap.put("paraTypeId", "300018");
                List<HashMap> kgList = (List<HashMap>)prodPreOrderMapperService.getHeaderByCfg(kgMap);
                if(kgList!=null && kgList.size() > 0){
                    String paraId = StringUtil.obj2Str(kgList.get(0).get("PARA_ID"));
                    if(StringUtil.isEqual(paraId,"0")){
                        retString = "";
                    }else {
                        retString = qryLogisticsInfo(retMap);
                    }
                }
                /*if(StringUtil.isNotEmptyOrNull(retString)){
                    JSONObject json = JSONObject.fromObject(retString);
                    JSONArray traces = json.optJSONArray("traces");
                    if (traces != null && traces.size() > 0) {
                        for (int i = 0; i < traces.size(); i++) {
                            JSONObject trace = traces.optJSONObject(i);
                            *//*状态转换*//*
    *//*                      集团状态。LOVB=EVT-C-0019
                            1000	待发货
                            1100	已通知揽收
                            1200	已发货
                            1300	已收货*//*

                            *//*ems侧状态*//*
    *//*                        00：收寄
                            10：妥投
                            20: 未妥投
                            30：经转过程中
                            40：离开处理中心
                            41：到达处理中心
                            50安排投递
                            51：正在投递
                            60：揽收*//*

                            String stausCd = StringUtil.obj2Str(trace.optString("code"));
                            String reMark = StringUtil.obj2Str(trace.optString("remark"));
                            String acceptTime = StringUtil.obj2Str(trace.optString("acceptTime"));
                            Map qryMap = new HashMap<>();
                            qryMap.put("paraTypeId", "300017");
                            qryMap.put("paraId", stausCd);
                            List<HashMap> outList = (List<HashMap>)prodPreOrderMapperService.getHeaderByCfg(qryMap);
                            if(outList!=null && outList.size() > 0){
                                String jtStatus = StringUtil.obj2Str(outList.get(0).get("PARA_VALUE_01"));
                                if(StringUtil.isNotEmptyOrNull(jtStatus)){
                                    Map traceMap = new HashMap<>();
                                    traceMap.put("statusCd", jtStatus);
                                    traceMap.put("remark", reMark);
                                    traceMap.put("statusDate", acceptTime);
                                    traceMap.put("receiverAddr", StringUtil.obj2Str(retMap.get("receiverAddr")));
                                    traceMap.put("custOrderLogisticsId", StringUtil.obj2Str(retMap.get("custOrderLogisticsId")));
                                    traceMap.put("custOrderId", StringUtil.obj2Str(retMap.get("custOrderId")));
                                    traceMap.put("receiverName", StringUtil.obj2Str(retMap.get("receiverName")));
                                    traceMap.put("logisticsCompany", StringUtil.obj2Str(retMap.get("logisticsCompany")));
                                    traceMap.put("logisticsNbr", StringUtil.obj2Str(retMap.get("logisticsNbr")));
                                    traceMap.put("postcode", StringUtil.obj2Str(retMap.get("postcode")));
                                    traceMap.put("receiverPhone", StringUtil.obj2Str(retMap.get("receiverPhone")));
                                    traceMap.put("commonRegionId", commonRegionId);
                                    retList.add(cnt, traceMap);
                                    cnt++;
                                }else {
                                    continue;
                                }
                            }
                        }
                    }else {
                        //如果查询不出结果，默认赋值
                        retMap.put("statusCd", "1200");
                        retList.add(retMap);
                    }
                }else {
                    //如果查询不出结果，默认赋值
                    retMap.put("statusCd", "1200");
                    retList.add(retMap);
                }
                //end by yinjj*/

                log.info("#######################queryCustOrderLogistics结束"+retList.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            throw new Exception(e.getMessage());
        }

        return retList;
    }

    //调接口查询ems物流信息
    private String qryLogisticsInfo(Map<String, String> resMap){
        String retStr = "";
        String logisticsNbr = StringUtil.obj2Str(resMap.get("logisticsNbr"));
        String logisticsCompany = StringUtil.obj2Str(resMap.get("logisticsCompany"));
        log.info("==logisticsNbr===="+logisticsNbr+"======logisticsCompany======"+logisticsCompany);
        //接口地址配置起来
        String paraId = "4";
        String url = invoiceInfoMapper.getInterfaceBill(paraId);
        if(StringUtil.isEmptyOrNull(url)){
            throw new RuntimeException("未查询到ems接口的地址");
        }
        url += "/"+logisticsNbr;
        try {
            retStr = soapClientService.remoteSoapClientInfoIml("ems", "", url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // TODO Auto-generated method stub
        return retStr;
    }
}
